package com.sofwin.controller;

import com.github.pagehelper.PageInfo;
import com.sofwin.Constants;
import com.sofwin.pojo.SysDept;
import com.sofwin.service.DeptService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.stream.IntStream;

/**
 * @packageName: com.sofwin.controller
 * @user: andyliu
 * @date: 2023/5/11 10:18
 * @email 115176513@qq.com
 * @description: TODO
 */
@Controller
@RequestMapping("dept")
public class DeptController {
    @Autowired
    private DeptService deptService;

    // 跳转到列表页的请求  分页数据
    @RequestMapping("list")
    public String data(Model model,SysDept dept, @RequestParam(required = true,defaultValue = "1") Integer pageNumber, @RequestParam(required = true,defaultValue = Constants.PAGE_SIZE) Integer pageSize){

        // 调用业务层查询分页数据
        PageInfo<SysDept> page = deptService.queryByPage(dept, pageNumber, pageSize);
        model.addAttribute("page",page);
        model.addAttribute("dept",dept);
        // 放到model作用域中
        return "dept/list";
    }

    // 跳转到编辑或新增页

    @GetMapping("toEdit")
    public String toEdit(Integer id,Model model){
        // 编辑和新增的区别
        // 编辑id不为空，需要查询当前的部门信息
        if(id!=null){
            SysDept sysDept = deptService.queryById(id);
            model.addAttribute("dept",sysDept);
        }
        return "dept/edit";
    }
    // 保存数据（新增或修改）

    @PostMapping("save")
    @ResponseBody
    public boolean save(SysDept dept){
        boolean status = deptService.saveOrUpdateDept(dept);
        return  status;
    }
    // 删除
    @DeleteMapping("delete/{id}")
    @ResponseBody
    public boolean delete(@PathVariable Integer id){
        boolean status = deptService.removeById(id);
        return status;
    }

    // 批量删除
    @DeleteMapping("deletes")
    @ResponseBody
    public boolean deletes( String ids){
        String[] idArray = ids.split(",");
        int[] ints = Arrays.stream(idArray).mapToInt(a -> {
            return new Integer(a);
        }).toArray();

        boolean status = deptService.removeById(ints);
        return status;
    }
    @RequestMapping("deletes2")
    @ResponseBody
    public boolean deletes2(@RequestParam(name="ids[]") Integer[] ids){

        boolean status = deptService.removeById(ids);
        return status;
    }
}
